#include "application.h"
#include "drv_l1_usbd.h"
#include "drv_l2_usbd_msdc.h"

/**************************************************************************
* 												 C O N S T A N T S															*
**************************************************************************/
enum
{
	USB_IDLE= 0,
	USB_MSDC,
	USB_UVC,
	USB_EXIT,
	USB_ERR
};

#define USB_TASK_QUEUE_MAX	32
void *usb_task_q_stack[USB_TASK_QUEUE_MAX];

/**************************************************************************
* 											 G L O B A L		D A T A 													*
**************************************************************************/
OS_EVENT *USBTaskQ;
OS_EVENT *USBCamApQ;
OS_EVENT *USBAudioApQ;

static INT32U usb_status = USB_IDLE;

#if ENABLE_REAR_SENSOR_FROM_HOST_UVC
extern void usb_phy_lock(void);
extern void usb_phy_unlock(void);
#endif
/**************************************************************************/
void state_usb_device_entry(void *para)
{
	INT32U	msg_id;
	INT16U	QReceiveTimeout = 0;
	INT8U	err;

	USBTaskQ = OSQCreate(usb_task_q_stack, USB_TASK_QUEUE_MAX);

	/* Set USB device speed, USB_SPEED_20 = high speed, USB_SPEED_11 = full speed */
	if(drv_l1_sys_extosc_get())
	{
		drv_l1_usbd_set_speed(USB_SPEED_20);
	}
	else
	{
		drv_l1_usbd_set_speed(USB_SPEED_11);
	}

	while(1)
	{
		msg_id = (INT32U) OSQPend(USBTaskQ, QReceiveTimeout, &err);

#if ENABLE_REAR_SENSOR_FROM_HOST_UVC
		usb_phy_lock();
#endif
		switch(msg_id)
		{
		case MSG_USBD_INITIAL:
		case MSG_USBCAM_INITIAL:
			usb_mode_detect();
			usb_status = USB_IDLE;
			QReceiveTimeout = 0;
			break;

		case MSG_USBD_PLUG_IN:
			if(usb_msdc_init() == 0)
			{
				usb_status = USB_MSDC;
				QReceiveTimeout = 100;	// 1s
			}
			break;

		case MSG_USBCAM_PLUG_IN:
			if(usb_uvc_init() == 0)
			{
				usb_status = USB_UVC;
				QReceiveTimeout = 0;
			}
			break;

		case MSG_USBCAM_PLUG_OUT:
			usb_status = USB_EXIT;
			usb_uvc_exit();
			QReceiveTimeout = 0;
			break;

		case MSG_USBD_PLUG_OUT:
			usb_status = USB_EXIT;
			usb_msdc_exit();
			QReceiveTimeout = 0;
			break;

		case MSG_CHARGE_PLUG_OUT:
			break;

		default:
			if(usb_status == USB_MSDC)
			{
				drv_l2_usbd_msdc_process_insertion();
			}

			break;
		}
#if ENABLE_REAR_SENSOR_FROM_HOST_UVC
		usb_phy_unlock();
#endif
	}
}
